//
//  AccountManageViewController.m
//  MoneyLog
//
//  Created by Max on 11-6-18.
//  Copyright 2011年 wicresoft. All rights reserved.
//

#import "AccountManageViewController.h"
#import "AccountViewController.h"
#import "AccountWrapper.h"

static NSString *kRowViewKey = @"rowViewKey";
static NSString *kRowItemKey = @"rowItemKey";

@implementation AccountManageViewController
@synthesize _tableView;
@synthesize dataSourceArray;
@synthesize displayType;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [_tableView release];
    [_textField release];
    [dataSourceArray release];
    
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"帐户管理";
    
    self.dataSourceArray =[[NSMutableArray alloc] initWithCapacity:1];
    
    // 返回按钮
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancelAction)];
    self.navigationItem.leftBarButtonItem = backButton;
    [backButton release]; 	
    
    UIBarButtonItem *editItem = [[UIBarButtonItem alloc] 
                                 initWithBarButtonSystemItem:UIBarButtonSystemItemEdit
                                 target:self
                                 action:@selector(editAction:)];
	self.navigationItem.rightBarButtonItem = editItem;
	[editItem release];    
    
    if (displayType == 1) {
        self.navigationItem.leftBarButtonItem = nil;
    }
    
    _tableView.tableFooterView.hidden = NO;
    
    UIView *headerView= [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 60)];
    
    UIButton *addButton = [UIButton buttonWithType:UIButtonTypeContactAdd];
    addButton.frame = CGRectMake(20, 30, 30, 30);
    addButton.backgroundColor = [UIColor clearColor];
    [addButton addTarget:self action:@selector(addAction) forControlEvents:UIControlEventTouchUpInside];
    [headerView addSubview:addButton];
    
    _textField = [[UITextField alloc] initWithFrame:CGRectMake(56,25,220, 36)];
    _textField.placeholder =@"请输入新帐户";
    _textField.borderStyle = UITextBorderStyleRoundedRect;
    _textField.textColor = [UIColor blackColor];
    _textField.font = [UIFont systemFontOfSize:20.0]; 
    _textField.autocorrectionType = UITextAutocorrectionTypeNo;	 
    _textField.keyboardType = UIKeyboardTypeDefault;	 
    _textField.returnKeyType = UIReturnKeyDone;
    _textField.clearButtonMode = UITextFieldViewModeWhileEditing;	
    
    _textField.delegate = self;	  
    
    [headerView addSubview:_textField];
      
    _tableView.tableHeaderView = headerView;
    [headerView release];
    
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated 
{
    [super viewWillAppear:animated];
    
    [self.navigationController setToolbarHidden:YES animated:YES];

    [self loadData];
    [self._tableView reloadData];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(void)setEditing:(BOOL)editing animated:(BOOL)animated
{
    [self._tableView beginUpdates];
    [self._tableView setEditing:editing animated:YES];
    [self._tableView endUpdates];
    
    [super setEditing:editing animated:animated];
}

#pragma mark - * Table view data source

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    //return [[self.dataSourceArray objectAtIndex:section] objectForKey:kSectionTitleKey];
    return nil;
}

- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section
{
    NSString *title = nil;
	
	return title;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    //#warning Potentially incomplete method implementation.
    // Return the number of sections.
    //return [self.dataSourceArray count];
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return [self.dataSourceArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    [cell.contentView addSubview:[[self.dataSourceArray objectAtIndex:indexPath.row] objectForKey:kRowViewKey]];
    
    return cell;
}

// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    AccountWrapper *account = [[self.dataSourceArray objectAtIndex:indexPath.row] objectForKey:kRowItemKey];
    
    if (account.system) {
        return NO;
    }
    else
    {
        return YES;
    }
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}

// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        AccountWrapper *account = [[self.dataSourceArray objectAtIndex:indexPath.row] objectForKey:kRowItemKey];
        if ( [g_Database accountDelete:account.id] ) {
            [self.dataSourceArray removeObjectAtIndex:indexPath.row];
            [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
        }
        else {
            
            UIAlertView *alertView = [[UIAlertView alloc] 
                                      initWithTitle:@"提示"
                                      message:@"删除失败了" 
                                      delegate:nil 
                                      cancelButtonTitle:@"确定" 
                                      otherButtonTitles:nil, nil];
            [alertView show];
            [alertView release];
        }

    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
    
}

- (void)tableView:(UITableView *)tableView willBeginEditingRowAtIndexPath:(NSIndexPath *)indexPath
{
	NSLog(@"section: %d, row: %d", indexPath.section, indexPath.row);
}

- (void)tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath
{
	NSLog(@"section: %d, row: %d", indexPath.section, indexPath.row);
}


// // Override to support rearranging the table view.
// - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
// {
// }
//
// // Override to support conditional rearranging of the table view.
// - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
// {
// // Return NO if you do not want the item to be re-orderable.
//     return YES;
// } 

#pragma mark - * Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [_textField resignFirstResponder];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    AccountWrapper *account =[[self.dataSourceArray objectAtIndex:indexPath.row] objectForKey:kRowItemKey];
    AccountViewController *controller = [[AccountViewController alloc] initWithNibName:@"AccountViewController" bundle:nil];
    controller.titleString = @"编辑帐户";
    controller.account = account;
    controller.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:controller animated:YES];
    [controller release];
}

#pragma mark - * UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
	// the user pressed the "Done" button, so dismiss the keyboard
	[textField resignFirstResponder]; 
	return YES;
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    [textField resignFirstResponder];
    if ([textField.text length] != 0) {
        
        AccountWrapper *account = [[AccountWrapper alloc] init];
        account.name = textField.text;
        
        if (![g_Database accountAdd:account]) {
            UIAlertView *alertView = [[UIAlertView alloc] 
                                      initWithTitle:@"提示"
                                      message:@"添加失败了" 
                                      delegate:nil 
                                      cancelButtonTitle:@"确定" 
                                      otherButtonTitles:nil, nil];
            [alertView show];
            [alertView release];
        }
        else {
            textField.text =@"";
            [self loadData];
            [self._tableView reloadData];
        }
    }
    
    return YES;
}

#pragma mark - * Actions

-(void)editAction:(id)sender{
    [_textField resignFirstResponder];
    [self setEditing:YES animated:YES]; 
    
    UIBarButtonItem *doneItem = [[UIBarButtonItem alloc] 
                                 initWithBarButtonSystemItem:UIBarButtonSystemItemDone
                                 target:self
                                 action:@selector(doneAction:)];
	self.navigationItem.rightBarButtonItem = doneItem;
	[doneItem release];    
}

-(void)doneAction:(id)sender {
    [_textField resignFirstResponder];
    [self setEditing:NO animated:YES]; 
    UIBarButtonItem *editItem = [[UIBarButtonItem alloc] 
                                 initWithBarButtonSystemItem:UIBarButtonSystemItemEdit
                                 target:self
                                 action:@selector(editAction:)];
	self.navigationItem.rightBarButtonItem = editItem;
	[editItem release];    
}


-(void)cancelAction {
    if (displayType == 0) {
        [self.parentViewController dismissModalViewControllerAnimated:YES];
    }
    else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

-(void)addAction {
    [_textField becomeFirstResponder];
}

-(void)loadData {
    NSMutableArray *array = [g_Database getAccountArray:@""];
    //self.dataSourceArray = array;
    [self.dataSourceArray removeAllObjects];
    for (AccountWrapper *account in array) {
        NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                                    account,kRowItemKey,
                                    [self tableCellView:account],kRowViewKey,nil];
        [self.dataSourceArray addObject:dictionary];
    }
    
    [array release];
}

-(id)tableCellView:(AccountWrapper *)account{
    UIView *view = [[[UIView alloc] init] autorelease];
    
    UILabel *nameLable = [[UILabel alloc] initWithFrame:CGRectMake(10, 4, 100, 26)];
    nameLable.textColor = [UIColor blackColor];
    nameLable.font = [UIFont systemFontOfSize:16];
    nameLable.text = account.name;
    
    UILabel *moneyLable = [[UILabel alloc] initWithFrame:CGRectMake(10, 34, 100, 10)];
    moneyLable.textColor = [UIColor blueColor];
    moneyLable.font = [UIFont systemFontOfSize:10];
    moneyLable.text = [NSString stringWithFormat:@"余额:%.2f",account.money];
    
    UILabel *typeLable = [[UILabel alloc] initWithFrame:CGRectMake(200, 4, 60, 40)];
    typeLable.font = [UIFont systemFontOfSize:14];
    typeLable.textAlignment = UITextAlignmentRight;
    typeLable.text = account.type;
    
    [view addSubview:nameLable];
    [view addSubview:moneyLable];
    [view addSubview:typeLable];
    
    [nameLable release];
    [moneyLable release];
    [typeLable release];
    
    return view;
}

@end
